<?php
$allRootCategories = Mage::helper('vendorconnect')->getAllRootCategories();
if ( $allRootCategories && is_array($allRootCategories) )
{
    $rootCategoryCollection = Mage::getResourceModel('catalog/category_collection')
         ->addAttributeToSelect('*')
         ->addAttributeToFilter('entity_id', $allRootCategories);
}
function addTreeSymbol($level=1)
{
    $html = '';
    for ( $i=1; $i <=$level; $i++ )
    {
        $html .= '___';    
    }
    return $html;
}
?>
<style type="text/css">
.vendor_category_tree li{
    cursor: pointer;
}
.vendor_category_tree_loadsubcategories b{
    border: 1px solid #808080;
    display: inline-block;
    height: 15px;
    line-height: 15px;
    text-align: center;
    width: 15px;
    display: none;
}
#category_tree_block .entry-edit-head{
    color:#fff;
    cursor: pointer;
}
</style>
<div id="category_tree_block">
    <h4 class="entry-edit-head">Category Filter</h4>
    <ul class="mincoding_hide vendor_category_tree" id="vendor_category_tree">
        <?php foreach ( $rootCategoryCollection as $rootCategory ): ?>
            <li onclick="selectCategoryIdForContractEdit(this,event);" id="<?php echo $rootCategory->getId() ?>"><b><?php echo $rootCategory->getName() ?></b>
                <?php $categoryCollection= $rootCategory->getChildrenCategories();  ?>    
                <?php if ( $categoryCollection->getSize()): ?>
                <ul>
                <?php foreach ( $categoryCollection as $category ): ?>
                    <li onclick="selectCategoryIdForContractEdit(this,event);" id="<?php echo $category->getId() ?>">|<?php echo addTreeSymbol(1) ?> <?php echo $category->getName() ?> 
                        
                        <?php $categoryLevel2Collection= $category->getChildrenCategories(); ?>
                        <?php if ( $categoryLevel2Collection->getSize()): ?>
                        <ul>
                        <?php foreach ( $categoryLevel2Collection as $level2Category ): ?>
                            <li onclick="selectCategoryIdForContractEdit(this,event);" id="<?php echo $level2Category->getId() ?>">|<?php echo addTreeSymbol(2) ?> <?php echo $level2Category->getName() ?> 
                            <strong class="vendor_category_tree_loadsubcategories" onclick="loadSubCategoriesForContractEdit(this,event);"><b title="Load sub categories">+</b></strong>
                                
                            </li> 
                        <?php endforeach; ?>
                        </ul>
                        <?php endif; ?>
                        
                    </li> 
                <?php endforeach; ?>
                </ul>
                <?php endif; ?>
                
            </li> 
        <?php endforeach; ?>
    
    </ul>
</div>

<input type="hidden" name="default_category_id" id="default_category_id" value="<?php echo $this->category_id ?>" />
<input type="hidden" name="current_category" id="current_category" value="<?php echo $this->category_id ?>" />
<input type="hidden" name="reset_filter" id="reset_filter" value="0" />

<script type="text/javascript" src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
jQuery.noConflict();
jQuery(document).ready(function(){
    
    jQuery('#category_tree_block .vendor_category_tree').hide();
    jQuery('#category_tree_block .entry-edit-head').click(function(){
        jQuery('.vendor_category_tree').toggle();        
    });
    
    //choose products
    jQuery(document).on('click','#catalog_category_products .grid .checkbox',function(){
        var checkbox_title = jQuery(this).attr('title');
        if ( checkbox_title != undefined )
        {
            //select all checkbox  
            var type = jQuery(this).is(':checked') ? 'add' : 'remove';
            jQuery( '#catalog_category_products .grid .checkbox' ).each(function( index ) {
                if ( jQuery(this).attr('title') == undefined )
                {
                    updateProductIds(jQuery(this).val(),type);        
                }
            });  
        }
        else
        {
            if ( !jQuery(this).is(':checked') )
            {
                updateProductIds(jQuery(this).val(),'remove');        
            }      
            else 
            {
                updateProductIds(jQuery(this).val(),'add');
            } 
        }
        updateProductIds();
        
    });
});
function updateProductIds(value,type)
{
    var selected_products = jQuery('#selected_products').val();
    if ( selected_products )
    {
        var productIds = selected_products.split(',');
        if ( type == 'add' )
        {
            if ( productIds.indexOf(value) == -1 ) jQuery('#selected_products').val( selected_products + ',' + value);    
        }   
        else if ( type == 'remove' ) {
            var checkedList = [];
            for ( var i = 0; i < productIds.length; i++ )
            {
                //console.log(productIds[i] + ' ' + value);
                if ( productIds[i] != value ) checkedList.push(productIds[i]);        
            }        
            jQuery('#selected_products').val(checkedList.join());  
        }    
    }
    else
    {
        //first adding
        if ( type == 'add' )
        {
            jQuery('#selected_products').val(value);    
        }    
    }
    //console.log(jQuery('#selected_products').val());    
}
function updateProductSelected()
{
    var selected_products = jQuery('#selected_products').val();
    var productIds = selected_products.split(',');
    if ( productIds.length )
    {
        jQuery( '#catalog_category_products .grid .checkbox' ).prop('checked',false);
        jQuery( '#catalog_category_products .grid .checkbox' ).each(function( index ) {
            if ( jQuery(this).attr('title') == undefined )
            {
                if ( productIds.indexOf(jQuery(this).val()) != -1 )
                {
                    jQuery(this).prop('checked',true);        
                }        
            }
        });    
    }
      
}

function loadSubCategoriesForContractEdit(element,event)
{
    alert('This function is undercontruction!');
    event.stopPropagation()
    return false;    
}
function selectCategoryIdForContractEdit(element,event)
{
    document.getElementById('current_category').value = element.id;
    document.getElementById('reset_filter').value = 0;
    catalog_category_productsJsObject.doFilter();
    event.stopPropagation()
    return false;    
}
varienGrid.prototype.resetFilter = function(){
    document.getElementById('reset_filter').value = 1;
    this.reload(this.addVarToUrl(this.filterVar, ''));
};
varienGrid.prototype.reload = function(url){
    if (!this.reloadParams) {
            this.reloadParams = {form_key: FORM_KEY};
        }
        else {
            this.reloadParams.form_key = FORM_KEY;
        }
        url = url || this.url;
        url = url + (url.match(new RegExp('\\?')) ? '&ajax=true' : '?ajax=true' );
        
        var needle_str = 'id/' + document.getElementById('default_category_id').value;
        // + '&category_id=' + document.getElementById('current_category').value;
        if ( document.getElementById('reset_filter').value != 1)
        {
            url = url.replace(needle_str,'id/' + document.getElementById('current_category').value);
            url += '&category_id=' + document.getElementById('current_category').value;    
        }
        
        console.log(url);
        
        if(this.useAjax){
            new Ajax.Request(url, {
                loaderArea: this.containerId,
                parameters: this.reloadParams || {},
                evalScripts: true,
                onFailure: this._processFailure.bind(this),
                onComplete: this.initGridAjax.bind(this),
                onSuccess: function(transport) {
                    try {
                        var responseText = transport.responseText.replace(/>\s+</g, '><');

                        if (transport.responseText.isJSON()) {
                            var response = transport.responseText.evalJSON()
                            if (response.error) {
                                alert(response.message);
                            }
                            if(response.ajaxExpired && response.ajaxRedirect) {
                                setLocation(response.ajaxRedirect);
                            }
                        } else {
                            /**
                             * For IE <= 7.
                             * If there are two elements, and first has name, that equals id of second.
                             * In this case, IE will choose one that is above
                             *
                             * @see https://prototype.lighthouseapp.com/projects/8886/tickets/994-id-selector-finds-elements-by-name-attribute-in-ie7
                             */
                            var divId = $(this.containerId);
                            if (divId.id == this.containerId) {
                                divId.update(responseText);
                            } else {
                                $$('div[id="'+this.containerId+'"]')[0].update(responseText);
                            }
                        }
                        
                        updateProductSelected();
                        
                    } catch (e) {
                        var divId = $(this.containerId);
                        if (divId.id == this.containerId) {
                            divId.update(responseText);
                        } else {
                            $$('div[id="'+this.containerId+'"]')[0].update(responseText);
                        }
                    }
                }.bind(this)
            });
            return;
        }
        else{
            if(this.reloadParams){
                $H(this.reloadParams).each(function(pair){
                    url = this.addVarToUrl(pair.key, pair.value);
                }.bind(this));
            }
            location.href = url;
        }
    
};
/*varienForm.prototype._submit = function(){
    alert($("selected_products").getValue());return false;
    var checkedList = [];
    $$('#catalog_category_products .checkbox').each(function(ele)
    {
        if( $(ele).checked )
        {
            checkedList.push($(ele).value);
        }
         
    });
    $("selected_products").setValue(checkedList.join());
    
    var $form = $(this.formId);
    if(this.submitUrl){
        $form.action = this.submitUrl;
    }
    $form.submit();
};*/
/*document.observe("dom:loaded", function(){
    $$('#catalog_category_products .checkbox').invoke('observe','click',function(field) {
        var checkedList = [];
        $$('#catalog_category_products .checkbox').each(function(ele)
        {
            if( $(ele).checked )
            {
                checkedList.push($(ele).value);
            }
        });
        
        $("selected_products").setValue(checkedList.join());
    });
    
});*/
</script>